import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/blueprint/ranking_model.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/parts/login_required_dialog.dart';

/// 排行榜视图模型
class LeaderboardNavigatorViewModel extends ReactiveViewModel {
  List<RankingUserModel> _rankingUsers = [];

  /// 获取排行榜用户列表
  List<RankingUserModel> get rankingUsers => _rankingUsers;

  /// 获取当前用户
  RankingUserModel? get currentUser {
    final currentUserModel = appState.userStore.currentUser;
    if (currentUserModel == null) return null;

    try {
      return _rankingUsers.firstWhere((user) => user.id == currentUserModel.id);
    } catch (e) {
      return null;
    }
  }

  /// 初始化排行榜数据
  void initializeLeaderboardData() {
    _rankingUsers = _generateRankingDataFromUsers();
    notifyListeners();
  }

  @override
  List<ReactiveServiceMixin> get reactiveServices => [appState.userStore];

  /// 从用户状态管理生成排行榜数据
  List<RankingUserModel> _generateRankingDataFromUsers() {
    final allUsers = appState.userStore.getAllUsers();

    // 为每个用户分配分数（admin用户分数最高）
    List<MapEntry<UserModel, int>> usersWithScores =
        allUsers.map((user) {
          int score;
          if (user.account == 'admin') {
            score = 5; // admin用户分数最高
          } else {
            // 其他用户根据ID分配递减分数
            final userId = int.tryParse(user.id) ?? 1;
            score = (6 - userId).clamp(1, 4); // 分数在1-4之间
          }
          return MapEntry(user, score);
        }).toList();

    // 按分数降序排序
    usersWithScores.sort((a, b) => b.value.compareTo(a.value));

    // 转换为排行榜用户模型
    List<RankingUserModel> rankingUsers = [];
    for (int i = 0; i < usersWithScores.length; i++) {
      final user = usersWithScores[i].key;
      final score = usersWithScores[i].value;

      rankingUsers.add(
        RankingUserModel(
          id: user.id,
          name: user.username,
          avatar: user.avatar,
          score: score,
          rank: i + 1,
        ),
      );
    }

    return rankingUsers;
  }
}

/// 排行榜页面
class RankListStory extends StatelessWidget {
  const RankListStory({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<LeaderboardNavigatorViewModel>.reactive(
      viewModelBuilder:
          () => LeaderboardNavigatorViewModel()..initializeLeaderboardData(),
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: SafeArea(
            bottom: false,
            child: Column(
              children: [
                // 顶部导航栏
                _constructNavigationBar(context),
                // 排行榜内容
                Expanded(
                  child: Column(
                    children: [
                      SizedBox(height: 24.h),
                      // 主体内容
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 44.h),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(MagmaConstant.rankBackground),
                              fit: BoxFit.cover,
                            ),
                            border: Border.all(
                              color: MagmaColor.white,
                              width: 1.w,
                            ),
                            borderRadius: BorderRadius.circular(2.r),
                          ),
                          child: Column(
                            children: [
                              SizedBox(height: 24.h),
                              // 排行榜标题
                              _displayLeaderboardTitle(),
                              SizedBox(height: 16.h),
                              // 虚线分隔符
                              _renderDashedLine(),
                              SizedBox(height: 16.h),
                              // 可滚动的排行榜列表
                              Expanded(
                                child: _renderScrollableLeaderboardList(
                                  viewModel,
                                ),
                              ),
                              SizedBox(height: 16.h),
                              // 当前用户排名
                              _renderCurrentUserRank(context, viewModel),
                              SizedBox(height: 16.h),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建导航栏
  Widget _constructNavigationBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        top: 16.h,
        bottom: 16.h,
      ),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => QR.back(),
            child: Image.asset(MagmaConstant.back, width: 20.w, height: 25.w),
          ),
          Spacer(),
          Text(
            'challenge',
          ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
          Spacer(),
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  /// 构建排行榜标题
  Widget _displayLeaderboardTitle() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 8.w,
          height: 8.w,
          decoration: BoxDecoration(
            color: MagmaColor.green,
            shape: BoxShape.circle,
          ),
        ),
        SizedBox(width: 8.w),
        Text('week').blackHanSans(fontSize: 18.sp, color: MagmaColor.white),
        SizedBox(width: 8.w),
        Container(
          width: 8.w,
          height: 8.w,
          decoration: BoxDecoration(
            color: MagmaColor.green,
            shape: BoxShape.circle,
          ),
        ),
      ],
    );
  }

  /// 构建虚线分隔符
  Widget _renderDashedLine() {
    return Container(
      width: double.infinity,
      height: 1.h,
      child: CustomPaint(painter: DashedLinePainter()),
    );
  }

  /// 构建可滚动的排行榜列表
  Widget _renderScrollableLeaderboardList(
    LeaderboardNavigatorViewModel viewModel,
  ) {
    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      itemCount: viewModel.rankingUsers.length,
      itemBuilder: (context, index) {
        final user = viewModel.rankingUsers[index];
        return _generateUserRankItem(user);
      },
    );
  }

  /// 构建用户排名项目
  Widget _generateUserRankItem(RankingUserModel user) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Row(
        children: [
          // 排名 - 固定宽度确保对齐
          SizedBox(
            width: 30.w,
            child: Text('${user.rank}').blackHanSans(
              fontSize: 18.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w600,
            ),
          ),
          SizedBox(width: 16.w),
          // 头像
          Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(shape: BoxShape.circle),
            child: ClipOval(
              child: Image.asset(
                user.avatar,
                fit: BoxFit.cover,
                width: double.infinity,
                height: double.infinity,
              ),
            ),
          ),
          SizedBox(width: 16.w),
          // 用户名
          Expanded(
            child: Text(user.name).blackHanSans(
              fontSize: 18.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w600,
            ),
          ),
          // 分数 - 固定宽度确保对齐
          SizedBox(
            width: 30.w,
            child: Align(
              alignment: Alignment.centerRight,
              child: Text('${user.score}').inter(
                fontSize: 20.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建当前用户排名
  Widget _renderCurrentUserRank(
    BuildContext context,
    LeaderboardNavigatorViewModel viewModel,
  ) {
    final currentUser = viewModel.currentUser;
    final isLoggedIn = appState.userStore.isLoggedIn;

    return GestureDetector(
      onTap: () {
        if (!isLoggedIn) {
          LoginRequiredDialog.show(
            context,
            title: 'Authentication Required',
            message: 'Please log in to view your ranking details.',
            confirmText: 'Login',
            cancelText: 'Cancel',
          );
        }
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MagmaConstant.rankMeCard),
            fit: BoxFit.cover,
          ),
        ),
        child: Row(
          children: [
            // 排名 - 固定宽度确保对齐
            SizedBox(
              width: 30.w,
              child: Text(
                isLoggedIn ? '${currentUser?.rank ?? 0}' : '--',
              ).blackHanSans(
                fontSize: 18.sp,
                color: MagmaColor.black,
                fontWeight: FontWeight.w600,
              ),
            ),
            SizedBox(width: 16.w),
            // 头像
            Container(
              width: 48.w,
              height: 48.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: MagmaColor.white, width: 1.w),
              ),
              child:
                  isLoggedIn && currentUser != null
                      ? ClipOval(
                        child: Image.asset(
                          currentUser.avatar,
                          fit: BoxFit.cover,
                          width: double.infinity,
                          height: double.infinity,
                        ),
                      )
                      : Container(
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: MagmaColor.white.withValues(alpha: 0.2),
                        ),
                        child: Icon(
                          Icons.person,
                          color: MagmaColor.black,
                          size: 20.w,
                        ),
                      ),
            ),
            SizedBox(width: 16.w),
            // 用户名
            Expanded(
              child: Text(
                isLoggedIn && currentUser != null ? currentUser.name : 'Guest',
              ).blackHanSans(
                fontSize: 18.sp,
                color: MagmaColor.black,
                fontWeight: FontWeight.w600,
              ),
            ),
            // "me" 标识
            Text('me').blackHanSans(
              fontSize: 18.sp,
              color: MagmaColor.black,
              fontWeight: FontWeight.w600,
            ),
          ],
        ),
      ),
    );
  }
}

/// 虚线绘制器
class DashedLinePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint =
        Paint()
          ..color = MagmaColor.white
          ..strokeWidth = 1.0
          ..style = PaintingStyle.stroke;

    const dashWidth = 6.0;
    const dashSpace = 6.0;
    double startX = 0;

    while (startX < size.width) {
      canvas.drawLine(
        Offset(startX, size.height / 2),
        Offset(startX + dashWidth, size.height / 2),
        paint,
      );
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
